package com.ys.cloudpicture.aop;

import com.ys.cloudpicture.annotation.AuthCheck;
import com.ys.cloudpicture.exception.BusinessException;
import com.ys.cloudpicture.exception.ErrorCode;
import com.ys.cloudpicture.model.enums.UserRoleEnum;
import com.ys.cloudpicture.model.vo.UserLoginVO;
import com.ys.cloudpicture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户权限校验切面
 */
@Component
@Aspect
public class AuthAspect {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     * @param authCheck
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doAuthCheck( ProceedingJoinPoint joinPoint,AuthCheck authCheck) throws Throwable {
        // 获取传入的参数权限
        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 不需要权限,直接放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 获取当前登录用户
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        UserLoginVO userLoginVO = userService.getLoginUser(request);
        // 获取用户权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userLoginVO.getUserRole());
        // 没有权限
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 要求管理员权限   但用户没有
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
